//
//  PurchaseViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/13.
//  Copyright © 2018年 张庆勇. All rights reserved.
//
#import "PurchaseViewController.h"
#import "TransactionHeadView.h"
#import "TransactionCell.h"
#import "JGPopView.h"
#import "TranOrder.h"
#import "AssetsModle.h"
#import "LoginViewController.h"
#import "OrdeDealsViewController.h"
#import "Y_StockChartViewController.h"
#import "LeftViewController.h"
#import "UIViewController+CWLateralSlide.h"
@interface PurchaseViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,strong) NSMutableArray * asksArray; //卖
@property (nonatomic,strong) NSMutableArray * bidsArray;//买
@property (nonatomic,strong) TransactionHeadView * tableviewHeadView;
@property (nonatomic,assign) NSInteger  buttonIndex;
@property (nonatomic,assign) NSInteger  chooseIndex;
@property (nonatomic,strong) UIView * buleView;
@property(nonatomic,strong) UIButton * leftButton;
@property(nonatomic,strong) UIButton * collectionbutton; //收藏
@property(nonatomic,assign) BOOL iscollection;
@property(nonatomic,assign) BOOL isSell; //是否是卖出还是买入
@property(nonatomic,assign) BOOL isResh; //是否需要刷新
@property(nonatomic,strong) NSString * sellAvailable; //卖出余额
@property(nonatomic,strong) NSString * purchaseAvailable; //买入余额
@property (nonatomic,strong)NoNetworkView * workView;
@end
@implementation PurchaseViewController
- (void)viewDidAppear:(BOOL)animated
{
//    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:WBSCOKETHOST_IP]; //开始连接
    if ([AppDelegate shareAppdelegate].isNoWork)
    {
        if ([AppDelegate shareAppdelegate].index == _index) {
            if (![[AppDelegate shareAppdelegate].modle.name isEqualToString:_name])
            {
                [self LoginSusess];
                [AppDelegate shareAppdelegate].index = 0;
                _index = [AppDelegate shareAppdelegate].index;
            }
        }else
        {
            _index = [AppDelegate shareAppdelegate].index;
            [self LoginSusess];
        }
    }else
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"transaction_Network") view:kWindow];
    }
    
}
- (void)viewWillAppear:(BOOL)animated
{
    _isResh = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
    _isResh = NO;
}

// 切换交易对
- (void)LoginSusess
{
    _modle = [AppDelegate shareAppdelegate].modle;
    if (![NSString isEmptyString:_modle.name]) {
        
        [self sleceButton:[AppDelegate shareAppdelegate].index];
        [_tableviewHeadView refushUIdataWithModle:[AppDelegate shareAppdelegate].modle];
        NSMutableArray * array = [ EXUnit getCollectionData];
        _iscollection = [array containsObject:[AppDelegate shareAppdelegate].modle.name];
        _collectionbutton.selected = _iscollection;
        _name = _modle.name;
        NSArray *namearray = [_name componentsSeparatedByString:@"_"];
        [_leftButton setTitle:[NSString stringWithFormat:@"%@ / %@",namearray[0],namearray[1]] forState:(UIControlStateNormal)];
        [_dataArray removeAllObjects];
        [_tableView reloadData];
        [_asksArray removeAllObjects];
        [_bidsArray removeAllObjects];
        [self getOrderQuery];//获取当前委托
        [self getbalance];
        
    }else
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"ransaction_currencies") view:kWindow];
    }
}
- (void)getOrderQuery
{
    NSArray * dataArray  = @[_modle.name,@20,@"0.00000001"];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"depth.subscribe" parameter:dataArray id:1763];
    [[SocketRocketUtility instance] sendData:data];   // 发送数据
}
#pragma mark - 导航栏控件
- (UIView *)leftItem
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    view.backgroundColor = [UIColor clearColor];
    _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(-10, 0, 130, 30)];
    _leftButton.titleLabel.font = AutoBoldFont(15);
    [_leftButton setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].symbolLefticon] forState:UIControlStateNormal];
    [_leftButton setTitle:[NSString stringWithFormat:@" %@",_modle.name] forState:(UIControlStateNormal)];
    [_leftButton setTitleColor:MAINTITLECOLOR forState:UIControlStateNormal];
    [_leftButton addTarget:self action:@selector(menu) forControlEvents:UIControlEventTouchUpInside];
    _leftButton.centerY = view.centerY;
    [_leftButton centerHorizontallyImageAndTextWithPadding:10];
//    _leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:_leftButton];
     return view;
}
- (void)menu
{
    [self defaultAnimationFromLeft];
}
// 查看k 线图
- (void)kChart
{
    if ([AppDelegate shareAppdelegate].isNoWork)
    {
        Y_StockChartViewController * Y_StockChartVC = [[Y_StockChartViewController alloc] init];
        Y_StockChartVC.modle = _modle;
        Y_StockChartVC.isHomePush = YES;
        Y_StockChartVC.isleftPush = NO;
        [self.navigationController pushViewController:Y_StockChartVC animated:YES];
    }else
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"transaction_Network") view:kWindow];
    }
}
// 收藏
- (void)Collection
{
    if (![AppDelegate shareAppdelegate].isNoWork)
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"transaction_Network") view:kWindow];
        return;
    }
    if (![EXUserManager isLogin])
    {
        [self SetLogin];
        return;
    }
    
    if (_iscollection) {
        [EXUnit removoveWithmarket:_modle.name];
        _collectionbutton.selected = NO;
        
    }else
    {
        [EXUnit saveCollectionDataUserDefaultsWith:_modle.name];
        _collectionbutton.selected = YES;
    }
    _iscollection = !_iscollection;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:CollectionNotificationse object:nil];
}
- (UIView *)rightItem
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    view.backgroundColor = [UIColor clearColor];
    UIButton * Barbutton = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 40, 30)];
    [Barbutton setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].symbolrighticon] forState:UIControlStateNormal];
  
    [Barbutton addTarget:self action:@selector(kChart) forControlEvents:UIControlEventTouchUpInside];
    [Barbutton sizeToFit];
    Barbutton.centerY = view.centerY;
    [view addSubview:Barbutton];
    _collectionbutton = [[UIButton alloc] initWithFrame:CGRectMake(60, 0, 40, 30)];
    [_collectionbutton setImage:[UIImage imageNamed:@"title-mark02"] forState:UIControlStateNormal];
    [_collectionbutton setImage:[UIImage imageNamed:@"title-mark01"] forState:UIControlStateSelected];
  
    [_collectionbutton addTarget:self action:@selector(Collection) forControlEvents:UIControlEventTouchUpInside];
    
    [_collectionbutton sizeToFit];
    _collectionbutton.centerY = view.centerY;
    [view addSubview:_collectionbutton];
    if ([[EXUnit getSite] isEqualToString:@"ZG"]) {
        UIButton * cUsbutton = [[UIButton alloc] initWithFrame:CGRectMake(26, 0, 40, 30)];
        [cUsbutton setImage:[UIImage imageNamed:@"us"] forState:UIControlStateNormal];
        [cUsbutton addTarget:self action:@selector(cUs) forControlEvents:UIControlEventTouchUpInside];
        [cUsbutton sizeToFit];
        cUsbutton.centerY = view.centerY;
        [view addSubview:cUsbutton];
    }
   
    return view;
}
/*联系我们*/
- (void)cUs
{
    QYSource *source = [[QYSource alloc] init];
    source.title = @"ZG.com";
    source.urlString = @"";
    QYSessionViewController *sessionViewController = [[QYSDK sharedSDK] sessionViewController];
    sessionViewController.sessionTitle = @"ZG.com";
    sessionViewController.source = source;
    sessionViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sessionViewController animated:YES];
}
// 仿QQ从左侧划出
- (void)defaultAnimationFromLeft {
    [_tableviewHeadView.numField resignFirstResponder];
    [_tableviewHeadView.priceField resignFirstResponder];
    // 自己随心所欲创建的一个控制器
    LeftViewController *vc = [[LeftViewController alloc] init];
    vc.drawerType = DrawerDefaultLeft; // 为了表示各种场景才加上这个判断，如果只有单一场景这行代码完全不需要
    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeDefault configuration:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAINCOLOR;
    self.navigationItem.title = @"";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftItem];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightItem];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(exitLogon) name:ManualExitLogonNotificationse object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdateBPrice:) name:updateSymbolNotificationse object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:WebSoketNotificationse object:nil];
    [self.view addSubview:self.tableView];
    self.isSell =NO;
    _chooseIndex = 1;
   
    
}
- (void)refreshData
{
    [_dataArray removeAllObjects];
    [_tableView reloadData];
    [self getOrderQuery];//获取当前委托
}
#pragma mark - button的点击事件
- (void)buttonbuyClick:(UIButton *)button
{
    [self sleceButton:button.tag];
}
- (void)sleceButton:(NSInteger)index
{
    WeakSelf
    [UIView animateWithDuration:0.25 animations:^{
        if (index ==0) {
            weakSelf.isSell = weakSelf.tableviewHeadView.sellButton.selected  = weakSelf.tableviewHeadView.buyButton.selected  = weakSelf.tableviewHeadView.isSell  =  NO;
            weakSelf.tableviewHeadView.purchaseButton.selected = YES;
            [AppDelegate shareAppdelegate].index = 0;
            weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:weakSelf.purchaseAvailable]];
            [weakSelf.tableviewHeadView refushUIdataWithModle:[AppDelegate shareAppdelegate].modle];
            
        }else
        {
            weakSelf.isSell = weakSelf.tableviewHeadView.buyButton.selected =  weakSelf.tableviewHeadView.isSell =  weakSelf.tableviewHeadView.sellButton.selected =  YES;
            weakSelf.tableviewHeadView.purchaseButton.selected = NO;
            weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:weakSelf.sellAvailable]];
            [weakSelf.tableviewHeadView refushUIdataWithModle:[AppDelegate shareAppdelegate].modle];
        }
       
      [weakSelf buyWithSell:weakSelf.isSell withLast:weakSelf.modle.last];
    }];
}

#pragma mark - 未登陆状态
- (void)exitLogon
{
     WeakSelf
    if ( weakSelf.isSell)
    {
        weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.base_asset_precision.intValue assess:weakSelf.sellAvailable]];
    }else
    {
        weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.base_asset_precision.intValue assess:weakSelf.purchaseAvailable]];
    }
    weakSelf.sellAvailable = @"";
    weakSelf.purchaseAvailable = @"";
    [weakSelf buyWithSell:weakSelf.isSell withLast:weakSelf.modle.last];
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
    [self orderWithType:_dataArray];

}
#pragma mark - 获取资产
- (void)getbalance
{
    if ([NSString isEmptyString:[EXUserManager userInfo].token])
    {
        [self exitLogon];
        return;
    }
    WeakSelf
    [HomeViewModel getUserAssetsWithDic:@{} url:Userassets homeModle:self.modle isSell:weakSelf.isSell callBack:^(BOOL isSuccess, NSString *sellAvailable, NSString *purchaseAvailable ,NSString * balance) {
    
        if (isSuccess) {
            weakSelf.sellAvailable = sellAvailable;
            weakSelf.purchaseAvailable = purchaseAvailable;
            
            if ( weakSelf.isSell) {
                 weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:weakSelf.sellAvailable]];
            }else
            {
                 weakSelf.tableviewHeadView.balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:weakSelf.purchaseAvailable]];
            }
           
            [weakSelf buyWithSell:weakSelf.isSell withLast:weakSelf.modle.last];
        }
    }];
    
}
/*可用可卖*/
- (void)buyWithSell:(BOOL)isBuy withLast:(NSString *)last
{
    WeakSelf
    NSArray *namearray = [weakSelf.modle.name componentsSeparatedByString:@"_"];
    if (!isBuy) {
        //可用
        NSString * buy = [EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:weakSelf.purchaseAvailable] ;
        weakSelf.tableviewHeadView.numLabValue.text = [NSString stringWithFormat:@"%@ %@ %@",Localized(@"transaction_available"),[NSString isEmptyString:buy]?@"0":buy,namearray[1]];
        //可卖
        NSString * sell = [EXUnit formatternumber:weakSelf.modle.base_asset_precision.intValue assess:[NSString stringWithFormat:@"%f",weakSelf.purchaseAvailable.floatValue/last.floatValue]];
        weakSelf.tableviewHeadView.sellnumLabValue.text = [NSString stringWithFormat:@"%@ %@ %@",Localized(@"transaction_buyNumberValue"),[NSString isEmailString:sell]?@"0":sell,namearray[0]];
        weakSelf.tableviewHeadView.buybalance = sell;
    }else
    {
        //可用
        NSString * buy = [EXUnit formatternumber:weakSelf.modle.base_asset_precision.intValue assess:weakSelf.sellAvailable] ;
        weakSelf.tableviewHeadView.numLabValue.text = [NSString stringWithFormat:@"%@ %@ %@",Localized(@"transaction_available"),[NSString isEmptyString:buy]?@"0":buy,namearray[0]];
        //可买
        NSString * sell = [EXUnit formatternumber:weakSelf.modle.quote_asset_precision.intValue assess:[NSString stringWithFormat:@"%f",weakSelf.sellAvailable.floatValue * last.floatValue]];
        weakSelf.tableviewHeadView.sellnumLabValue.text = [NSString stringWithFormat:@"%@ %@ %@",Localized(@"transaction_sellNumberValue"),[NSString isEmailString:sell]?@"0":sell,namearray[1]];
    }
}

#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - 49 - kStatusBarAndNavigationBarHeight  - IPhoneBottom)style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[TransactionCell class] forCellReuseIdentifier:@"TransactionCell"];
        _tableView.tableHeaderView =self.tableviewHeadView;
    }
    return _tableView;
}
- (TransactionHeadView*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        _tableviewHeadView =[[ TransactionHeadView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, RealValue_W(720))];
        _tableviewHeadView.buySuccess = ^(BOOL isSuccess) {
            if (isSuccess) {
                [weakSelf getbalance];
            };
        };
        _tableviewHeadView.buttonBlock = ^(UIButton *button) {
            
            [weakSelf buttonbuyClick:button];
        };
        _tableviewHeadView.askAndbidBlock  = ^(UIButton *button) {
            
            [weakSelf askAndbidButtonClick:button];
        };
        _tableviewHeadView.priceBlock = ^(NSString *price) {
            
//            [weakSelf buyWithSell:weakSelf.isSell withLast:price];
        };
    }
    return _tableviewHeadView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSMutableArray *)asksArray
{
    if (!_asksArray) {
        _asksArray = [[NSMutableArray alloc]init];
    }
    return _asksArray;
}
- (NSMutableArray *)bidsArray
{
    if (!_bidsArray) {
        _bidsArray = [[NSMutableArray alloc]init];
    }
    return _bidsArray;
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RealValue_W(188);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return RealValue_W(88);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TransactionCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"TransactionCell"];
    cell.homeMoel = _modle;
      WeakSelf
    if (_buttonIndex ==1)
    {
        
        cell.hiustModle = self.dataArray[indexPath.row];
        [cell.revokebutton setTitle:Localized(@"transaction_Detailed") forState:(UIControlStateNormal)];
        [cell.revokebutton add_BtnClickHandler:^(NSInteger tag) {
            [weakSelf orderdealsWithindexPath:indexPath array:self.dataArray];
        }];
        
    }else
    {
        cell.orderModle = self.dataArray[indexPath.row];
        WeakObject(cell)
        [cell.revokebutton add_BtnClickHandler:^(NSInteger tag) {
            [weakSelf revokeWith:indexPath with:self.dataArray button:weakcell.revokebutton];
            weakcell.revokebutton.enabled = NO;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakcell.revokebutton.enabled = YES;
            });
        }];
        [cell.revokebutton setTitle:Localized(@"transaction_Revoke") forState:(UIControlStateNormal)];
    }
    return cell;
    
}
#pragma  mark -----点击按钮查看订单
- (void)orderdealsWithindexPath:(NSIndexPath *)indexPath array:(NSMutableArray *)array
{
    TranOrder *orderModle = array[indexPath.row];
    OrdeDealsViewController * orderdealsVC = [[OrdeDealsViewController alloc] init];
    orderdealsVC.title = Localized(@"Business_details");
    NSArray *data = [orderModle.market componentsSeparatedByString:@"_"];
    orderdealsVC.makes = data;
    orderdealsVC.orderId = orderModle.id;
    if (orderModle.side.integerValue ==2)
    {
        orderdealsVC.isSell = NO;
    }else
    {
        orderdealsVC.isSell = YES;
    }
    
    [self.navigationController pushViewController:orderdealsVC animated:YES];
}
#pragma  mark -----点击cell 查看订单
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_buttonIndex ==1) {
        TranOrder *orderModle = _dataArray[indexPath.row];
        OrdeDealsViewController * orderdealsVC = [[OrdeDealsViewController alloc] init];
        orderdealsVC.title = Localized(@"Business_details");
        NSArray *data = [orderModle.market componentsSeparatedByString:@"_"];
        orderdealsVC.makes = data;
        orderdealsVC.orderId = orderModle.id;
        if (orderModle.side.integerValue ==2)
        {
            orderdealsVC.isSell = NO;
        }else
        {
            orderdealsVC.isSell = YES;
        }
        [self.navigationController pushViewController:orderdealsVC animated:YES];
    }
}
#pragma  mark -----取消订单
- (void)revokeWith:(NSIndexPath *)indexPath with:(NSMutableArray *)sourceArray button:(UIButton *)button
{
    button.userInteractionEnabled = NO;
    TranOrder * modle = sourceArray[indexPath.row];
    WeakSelf
    if (![NSString isEmptyString:[EXUserManager userInfo].token]) {
        
        [HomeViewModel getCancelOrderWithDic:@{@"market":_modle.name,@"order_id":modle.id} url:cancelOrder callBack:^(BOOL isSuccess, id callBack) {
            button.userInteractionEnabled = YES;
            if (isSuccess) {
                [weakSelf getbalance];
                [sourceArray removeObjectAtIndex:indexPath.row];
                [weakSelf.tableView reloadData];
                 [EXUnit showMessage:Localized(@"transaction_Revoke_success")];
            }else
            {
                button.userInteractionEnabled = YES;
            }
        }];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray * titles = @[Localized(@"transaction_entrustment"),Localized(@"transaction_Historical_records")];
    UIView *BgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth,RealValue_W(88))];
    BgView.backgroundColor = TABLEVIEWLCOLOR;
    CGFloat x = 0.0, y = 6, width = 0.0, height = 60/2,spacing = 0.0;
    x = 25/2;
    width = 124/2;
    spacing = (width+15);
    UIButton * Button;
    for (int i=0; i<titles.count; i++) {
        UIButton * newButton = [[UIButton alloc] initWithFrame:CGRectMake(x +i*spacing, y,  width, height)];
        [newButton setTitle:titles[i] forState:UIControlStateNormal];
        [newButton setTitleColor:MAINTITLECOLOR forState:UIControlStateSelected];
        [newButton setTitleColor:MAINTITLECOLOR1 forState:UIControlStateNormal];
        [newButton addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        newButton.tag = i;
        [BgView addSubview:newButton];
        newButton.selected = (i == self.buttonIndex)? YES:NO;
        if (newButton.selected) {
            newButton.titleLabel.font = AutoBoldFont(14);
        }else
        {
            newButton.titleLabel.font = AutoBoldFont(14);
        }
        if (newButton.selected) {
            Button = newButton;
        }  
    }
    _buleView = [[UIView alloc] initWithFrame:CGRectMake(x, RealValue_W(88) - RealValue_W(6), 30, 3)];
    _buleView.backgroundColor = [ZBLocalized sharedInstance].segmentBaColor;
    _buleView.centerX = Button.centerX;
    [BgView addSubview:_buleView];
    return BgView;
}
- (CGFloat )tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (_dataArray.count >3)
    {
        return 0.00;
    }else
    {
        return 160;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    view.backgroundColor = TABLEVIEWLCOLOR;
    return view;
}
#pragma  mark -----委托和历史记录选择栏
- (void)buttonClick:(UIButton *)buttonClick
{
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
    WeakSelf
    if (buttonClick.tag==0) {
        weakSelf.buttonIndex = 0;
        if (![EXUserManager isLogin]&& _dataArray.count==0) {
            
            [self.tableView reloadData];
        }else
        {
            [self getquery];
        }
    }else
    {
        weakSelf.buttonIndex = 1;
        if (![EXUserManager isLogin]&& _dataArray.count ==0) {
            [self.tableView reloadData];
        }else
        {
            weakSelf.buttonIndex = 1;
            [self getHistory:0];
        }
        
    }
    [UIView animateWithDuration:0.25 animations:^{
        
        weakSelf.buleView.centerX =  buttonClick.centerX;
        
    }];
   
    
}
// 获取委托list
- (void)getquery
{
    NSArray * dataArray  = @[_modle.name,@0,@20];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"order.query" parameter:dataArray id:1700];
    [[SocketRocketUtility instance] sendData:data];    // 发送数据
}
// 获取历史list
- (void)getHistory:(NSInteger)side
{
    NSArray * dataArray  = @[_modle.name,@0,@0,@0,@20,@(side)];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"order.history" parameter:dataArray id:1894];
    [[SocketRocketUtility instance] sendData:data];    // 发送数据
}
- (void)UpdateBPrice:(NSNotification *)message
{
    WeakSelf
    HomeModle * modle = message.object;
    if (modle.name ==_modle.name) {
         _modle = modle;
        NSString * range;
        float _x = modle.IncreaseDegree.floatValue;
        if (!isnan(_x)) {
            if (modle.last.floatValue - modle.open.floatValue >=0) {
                range = [NSString stringWithFormat:@"+ %.2f%%",modle.IncreaseDegree.floatValue];
                // 回到主队列刷新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                   weakSelf.tableviewHeadView.priceLable.textColor = ZHANGCOLOR;
                    weakSelf.tableviewHeadView.rangeLable.textColor = ZHANGCOLOR;
                });
                
            }else
            {
                range = [NSString stringWithFormat:@"%.2f%%",modle.IncreaseDegree.floatValue];
                // 回到主队列刷新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.tableviewHeadView.priceLable.textColor =DIEECOLOR;
                    weakSelf.tableviewHeadView.rangeLable.textColor = DIEECOLOR;
                });
               
            }
            
        }else
        {
            range = @"0.00%";
        }
        
        _tableviewHeadView.priceLable.text = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:modle.quote_asset_precision.intValue assess:modle.last]];
        _tableviewHeadView.rangeLable.text = range;
        return;
        
    }
}
- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    
    if (!_isResh) {
        return;
    }
    //收到服务端发送过来的消息
    NSString * message = note.object;
    if ([NSString isEmptyString:message]) {
        return;
    }
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
  
    
    WeakSelf
    if ([NSString isEmptyString:message1[@"id"]]) {
        NSArray * data = message1[@"params"];
        /*交易逻辑 */
        if ([message1[@"method"] isEqualToString:@"depth.update"])
        {
           
            dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 处理耗时操作在此次添加
                
                if (data.count>0) {
                    NSDictionary * asks = data[1];
                    NSArray * asksArray = asks[@"asks"];
                    NSArray *bidsArray = asks[@"bids"];
                    
                    if (asksArray.count>9 &&bidsArray.count>9) {
                        //                这里只截取前五条
                        [weakSelf.asksArray removeAllObjects];
                        [weakSelf.bidsArray removeAllObjects];
                        NSArray *ask;
                        NSArray *bids;
                        if (asksArray.count>10) {
                            ask = [asksArray subarrayWithRange:NSMakeRange(0, 10)];
                        }else
                        {
                            ask = asksArray;
                        }
                        if (bidsArray.count>10) {
                            bids = [bidsArray subarrayWithRange:NSMakeRange(0, 10)];
                        }else
                        {
                            bids = bidsArray;
                        }
                        
                        weakSelf.asksArray = [NSMutableArray arrayWithArray:ask];
                        weakSelf.bidsArray = [NSMutableArray arrayWithArray:bids];
                        [weakSelf resushAskbidTableViewWithIndex:weakSelf.chooseIndex];
                        
                    }else
                    {
                
                        if (asksArray.count>0)
                        {
                            
                            weakSelf.asksArray = [EXUnit getNewAsksArrayWithData:asksArray withArray:self.asksArray model:weakSelf.modle];
                          
                        }
                        if (bidsArray.count>0)
                        {
                            weakSelf.bidsArray = [EXUnit getNewbidsArrayWithData:bidsArray withArray:self.bidsArray model:weakSelf.modle];
        
                        }
                        
                        [weakSelf resushAskbidTableViewWithIndex:weakSelf.chooseIndex];
                        
                    }
                    
                }
                
            });
            
            if ([EXUserManager isLogin]) {
                if (weakSelf.buttonIndex ==0) {
                    [weakSelf getquery];
                }else
                {
                    [weakSelf getHistory:0];
                }
            }
            
           
            
        }
    }else if ([message1[@"id"] integerValue] ==1700)
    {
        
        if ([message1[@"result"] isEqual:[NSNull null]]) {
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf orderWithType:weakSelf.dataArray];
            
            return;
        }
        NSArray * data = message1[@"result"][@"records"];
        weakSelf.dataArray = [TranOrder mj_objectArrayWithKeyValuesArray:data];
        
        [weakSelf.tableView reloadData];
        [weakSelf orderWithType:weakSelf.dataArray];
        
    }else if ([message1[@"id"] integerValue] ==1894)
    {
        if ([message1[@"result"] isEqual:[NSNull null]]) {
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf orderWithType:weakSelf.dataArray];
            
            return;
        }
        NSArray * data = message1[@"result"][@"records"];
        weakSelf.dataArray = [TranOrder mj_objectArrayWithKeyValuesArray:data];
        
        [weakSelf.tableView reloadData];
        [weakSelf orderWithType:_dataArray];
    }
}
-(void)askAndbidButtonClick:(UIButton *)button
{
    _chooseIndex = button.tag;
    [self resushAskbidTableViewWithIndex:_chooseIndex];
}
- (void)resushAskbidTableViewWithIndex:(NSInteger)index
{
    WeakSelf
    switch (index) {
        case 0:
        {
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableviewHeadView getDepthDataWithasks:[self getlisthighAry:self.asksArray] bids:@[] rangeIndex:10];
            });
            
        }
           
            break;
        case 1:
        {
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf.tableviewHeadView getDepthDataWithasks:[self getlisthighAry:self.asksArray] bids: [self getlisthighAry:self.bidsArray]rangeIndex:5];
            });
            
        }
           
            break;
        case 2:
        {
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableviewHeadView getDepthDataWithasks:@[] bids: [self getlisthighAry:self.bidsArray]rangeIndex:10];
            });
            
        }
           
            break;
            
        default:
            break;
    }
}
- (void)orderWithType:(NSArray *)dataArray
{
    if (dataArray.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:CGRectMake(0, RealValue_W(88) + RealValue_W(720)+10, UIScreenWidth, 160) NoNetwork:NO];
        [self.tableView addSubview:_workView];
        [self.tableView bringSubviewToFront:_workView];
    }else
    {
        [_workView dissmiss];
    }
    
}
- (void)SetLogin
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
//升序
- (NSArray *)getlisthighAry:(NSArray *)Array
{
    NSLog(@"--->%@",Array);
    if (Array != nil) {
        //对数组进行排序
        NSArray  *ary = [Array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:obj1[0]];
            NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:obj2[0]];
            NSComparisonResult result_clearrate_float = [number compare:number1];
            if (result_clearrate_float==NSOrderedAscending)
            {
                return NSOrderedDescending;
            }
            else
            {
                return NSOrderedAscending;
            }
        }];
        return ary;
    }else
    {
        return Array;
    }
   
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
